<?php
require_once ('config.php');
require_once ('databasefunctions.php');
require_once ('displayfunctions.php');
require_once ('businessfunctions.php');
if (! session_is_registered('input_client')) session_register('input_client');
if (! session_is_registered('input_time')) session_register('input_time');
if (! session_is_registered('remark')) session_register('remark');
if (! session_is_registered('grid')) session_register('grid');
validate_user();
html_header();

function cmp_client_time($a, $b) {
        // for user define sort "usort" function below
        // sorting array $slot by column (company / client / job) then by row (time)
        $temp1 = $a['client'] . $a['time'];
        $temp2 = $a['client'] . $b['time'];
        $result = strcmp($temp1, $temp2);
        return $result;
}

switch ($_GET['action']) {
        case "save" :
                // AG: save values for subsequent input
                $_SESSION["TSsaved"]=$_GET;

                // obtain default company of timesheet staff
                $sql = "SELECT CompanyID FROM staffmaster WHERE StaffID = '" . $_GET['StaffID'] . "'";
                $sql_result = sql_execute($sql);
                $sql_data = mysql_fetch_array($sql_result);
                $DefaultCompany = $sql_data['CompanyID'];

                // store GET values into variables and convert to upper case
                $ClientID[0] = strtoupper($_GET['Client0']);
                $ClientID[1] = strtoupper($_GET['Client1']);
                $ClientID[2] = strtoupper($_GET['Client2']);
                $ClientID[3] = strtoupper($_GET['Client3']);
                $ClientID[4] = strtoupper($_GET['Client4']);
                $ClientID[5] = strtoupper($_GET['Client5']);
                $ClientID[6] = strtoupper($_GET['Client6']);
                $ClientID[7] = strtoupper($_GET['Client7']);
                $ClientID[8] = strtoupper($_GET['Client8']);
                $ClientID[9] = strtoupper($_GET['Client9']);

                $CompanyID[0] = strtoupper($_GET['Company0']);
                $CompanyID[1] = strtoupper($_GET['Company1']);
                $CompanyID[2] = strtoupper($_GET['Company2']);
                $CompanyID[3] = strtoupper($_GET['Company3']);
                $CompanyID[4] = strtoupper($_GET['Company4']);
                $CompanyID[5] = strtoupper($_GET['Company5']);
                $CompanyID[6] = strtoupper($_GET['Company6']);
                $CompanyID[7] = strtoupper($_GET['Company7']);
                $CompanyID[8] = strtoupper($_GET['Company8']);
                $CompanyID[9] = strtoupper($_GET['Company9']);

                $JobID[0] = strtoupper($_GET['Job0']);
                $JobID[1] = strtoupper($_GET['Job1']);
                $JobID[2] = strtoupper($_GET['Job2']);
                $JobID[3] = strtoupper($_GET['Job3']);
                $JobID[4] = strtoupper($_GET['Job4']);
                $JobID[5] = strtoupper($_GET['Job5']);
                $JobID[6] = strtoupper($_GET['Job6']);
                $JobID[7] = strtoupper($_GET['Job7']);
                $JobID[8] = strtoupper($_GET['Job8']);
                $JobID[9] = strtoupper($_GET['Job9']);

                // verify existence of company ID
                // Step 1. use Company ID to create a sql criteria string
                foreach ($CompanyID as $value) {
                        if (! empty($value)) $company_list .= "'$value' || ";
                }
                $string_length = strlen($company_list) - 3 ;
                $company_list = substr($company_list, 0, $string_length);

                // Step 2. obtain company list from database and group into $company_array
                if ($company_list) {
                        $sql = "SELECT CompanyID FROM companymaster WHERE Enable = 1 AND CompanyID = ($company_list)";
                        $sql_result = sql_execute($sql);
                        while ($sql_data = mysql_fetch_array($sql_result)) {
                                $company_array[] = $sql_data['CompanyID'];
                        }
                }

                // Step 3. check existence of input company id with company list from database
                for ($i = 0; $i < 10; $i++) {
                        if (! empty($CompanyID[$i])) {
                                if (! in_array($CompanyID[$i], $company_array)) {
                                        $error_text .= "<br>- $langcompanyid : " . $CompanyID[$i] . " $langnotexist<br>";
                                }
                        }
                }

                // verify existence of job ID
                // Step 1. use Job ID to create a sql criteria string
                foreach ($JobID as $value) {
                        if (! empty($value)) $job_list .= "'$value' || ";
                }
                $string_length = strlen($job_list) - 3 ;
                $job_list = substr($job_list, 0, $string_length);

                // Step 2. obtain job list from database and group into $job_array
                if ($job_list) {
                        $sql = "SELECT JobID FROM jobmaster WHERE Enable = 1 AND JobID = ($job_list)";
                        $sql_result = sql_execute($sql);
                        while ($sql_data = mysql_fetch_array($sql_result)) {
                                $job_array[] = $sql_data['JobID'];
                        }
                }

                // Step 3. check existence of input job id with job list from database
                for ($i = 0; $i < 10; $i++) {
                        if (! empty($JobID[$i])) {
                                if (! in_array($JobID[$i], $job_array)) {
                                        $error_text .= "<br>- $langjobid : " . $JobID[$i] . " $langnotexist<br>";
                                }
                        }
                }

                // verify existence of client ID
                $number_of_clients = 0;
                // Step 1. use Client ID to create a sql criteria string
                foreach ($ClientID as $value) {
                        if (! empty($value)) {
                                $client_list .= "'$value' || ";
                                $number_of_clients += 1;
                        }
                }
                $string_length = strlen($client_list) - 3 ;
                $client_list = substr($client_list, 0, $string_length);

                // Step 2. obtain client list from database and group into $client_array
                if ($client_list) {
                        $sql = "SELECT ClientID FROM clientmaster WHERE Enable = 1 AND ClientID = ($client_list)";
                        $sql_result = sql_execute($sql);
                        while ($sql_data = mysql_fetch_array($sql_result)) {
                                $client_array[] = $sql_data['ClientID'];
                        }
                }

                // Step 3. check existence of input client id with client list from database
                for ($i = 0; $i < 10; $i++) {
                        if (! empty($ClientID[$i])) {
                                if (! in_array($ClientID[$i], $client_array)) {
                                        $error_text .= "<br>- $langclientid : " . $ClientID[$i] . " $langnotexist<br>";
                                }
                        }
                }

                // verify at least one client
                if ($number_of_clients == 0) {
                        if (! $_SESSION['grid']) $error_text .= "<br>- $langnoclient<br>";
                }

                // verify the client / job / company are entered correctly
                for ($i = 0; $i < 10; $i++) {
                        if (! empty($ClientID[$i]) || ! empty($CompanyID[$i]) || ! empty($JobID[$i])) {
                                // Job ID and Client ID cannot be empty
                                if (empty($ClientID[$i]) || empty($JobID[$i])) {
                                        $warning_column = $i + 1;
                                        $error_text .= "<br>- $langblank $langclientid / $langcompanyid / $langjobid ";
                                        $error_text .= " $langcolnotallow $warning_column<br>";
                                }
                                // if no Company ID, take default company of timesheet staff member
                                if (empty($CompanyID[$i])) $CompanyID[$i] = $DefaultCompany;
                        }
                }

                // verify no duplicate company-client-job combination
                for ($i = 0; $i < 10; $i++) {
                        for ($j = 0; $j < 10; $j++) {
                                if ($i != $j) {
                                        if ($ClientID[$i] == $ClientID[$j] && $CompanyID[$i] == $CompanyID[$j] &&
                                                $JobID[$i] == $JobID[$j] && ! empty($ClientID[$i]) && ! empty($CompanyID[$i])
                                                && ! empty($JobID[$i])) {
                                                $source_column = $i + 1;
                                                $duplicate_column = $j + 1;
                                                $error_text .= "<br>- $langcompanyid / $langjobid / $langclientid $langcolduplicate";
                                                $error_text .= " $source_column $langand $duplicate_column<br>";
                                        }
                                }
                        }
                }

                // save time / client values into array
                $var_from_http_get = array_keys($_GET);

                foreach ($var_from_http_get as $input) {
                        // pool all time slot into variable $slot
                        if (substr($input,0,1) == 'X' && substr($input,2,1) == 'Y') {
                                $slot[] = array('client' => substr($input,1,1), 'time' => substr($input,3,3));
                        }
                }

                // same time slot should not have more than 1 client
                if (! empty($slot)) {
                        foreach ($slot as $value) {
                                $time_slot = $value['time'];
                                $client_slot = $value['client'];
                                // take 1 time slot value and compare with the reset of the time slot values
                                foreach ($var_from_http_get as $input)        {
                                        if (substr($input,0,1) == 'X' && substr($input,2,1) == 'Y') {
                                                $client = substr($input,1,1);
                                                $time = substr($input,3,3);
                                                if ($time == $time_slot && $client != $client_slot) {
                                                        $source_client = $client_slot + 1;
                                                        $target_client = $client + 1;
                                                        $time = get_time_from_time_slot($time_slot);
                                                        $error_text .= "<br>- $langclientcolumn $source_client $langduplicatetime ";
                                                        $error_text .= "$target_client $langat $time<br>";
                                                }
                                        }
                                }

                                if ($_SESSION['grid']) {
                                        // take 1 time slot value and compare with billed time slot values
                                        foreach ($_SESSION['grid'] as $x => $y) {
                                                $last_saved_time = array_keys($y);
                                                foreach ($last_saved_time as $time) {
                                                        if ($time == $time_slot && $_SESSION['grid'][$x][$time] == 'BILLED') {
                                                                $source_client = $client_slot + 1;
                                                                $target_client = $x + 1;
                                                                $time = get_time_from_time_slot($time_slot);
                                                                $error_text .= "<br>- $langclientcolumn $source_client $langduplicatetime ";
                                                                $error_text .= "$target_client $langat $time<br>";
                                                        }
                                                }
                                        }
                                }
                        }
                }
                else {
                        if (! $_SESSION['grid']) {
                                $error_text .= "<br>- $langnotimeselected $langanyclient<br>";
                        }
                }

                // each time slot should have client ID
                // no slot is also valid as there may be a user clearing his / her last saved timesheet
                if ($slot) {
                        foreach ($slot as $value) {
                                $client_slot = $value['client'];
                                if (empty($ClientID[$client_slot])) {
                                        $slot_column = $client_slot + 1;
                                        $time = get_time_from_time_slot($value['time']);
                                        $error_text .= "<br>- $langnoclientname $slot_column $langat $time<br>";
                                }
                        }
                }

                // each client should have at least one time slot
                foreach ($ClientID as $index => $client) {
                        if (! empty($client)) {
                                $time_slot = 0;
                                if ($slot) {
                                        foreach ($slot as $value) {
                                                // check whether this column has time slot selected
                                                if ($value['client'] == $index) $time_slot = 1;
                                        }
                                }

                                // if this column contains billed time slot, no new time slot is still valid
                                if ($_SESSION['grid'][$index]) {
                                        foreach ($_SESSION['grid'][$index] as $y) {
                                                if ($y == 'BILLED')        $time_slot = 1;
                                        }
                                }

                                if ($time_slot == 0) {
                                        $client_col = $index + 1;
                                        $error_text .= "<br>- $langclientcolumn : $client_col - $langnotimeselected<br>";
                                }
                        }
                }


                // calculate charge rate
                $staff_grade = get_staff_grade($_GET['StaffID']);
                foreach ($ClientID as $index => $client) {
                        if (! empty($client)) {
                                $charge_rate = get_charge_rate($staff_grade, $CompanyID[$index],
                                                           $ClientID[$index], $JobID[$index],
                                                           convert_unix_to_mysql_date($_GET['input_date']),$tax_rate);
                                if (! $charge_rate) {
                                        $client_col = $index + 1;
                                        $error_text .= "<br>- $langclientcolumn : $client_col - $langnochargerate<br>";
                                }
                                else {
                                        $ChargeRate[$index] = $charge_rate;
                                        $TaxRate[$index]    = $tax_rate;
                                }
                        }
                }



                // end of timesheet verification, show error message (if any)
                if ($error_text) {
                        // unset session variable
                        unset ($_SESSION['input_company']);
                        unset ($_SESSION['input_job']);
                        unset ($_SESSION['input_client']);
                        unset ($_SESSION['input_time']);

                        // load last input values into session variable
                        foreach ($ClientID as $value) $_SESSION['input_client'][] = $value;
                        foreach ($CompanyID as $value) $_SESSION['input_company'][] = $value;
                        foreach ($JobID as $value) $_SESSION['input_job'][] = $value;
                        foreach ($slot as $value) $_SESSION['input_time'][] = $value;

                        // display error message
                        message_box($error_text);
                        echo "<script>this.location='timesheet.php?StaffID=" . $_GET['StaffID']
                                 . "&inputdate=" . $_GET['input_date'] . "'</script>";
                        exit;
                }
                else {
                        $date_text = convert_unix_to_mysql_date($_GET['input_date']);

                        // remove unbilled old timesheet data in table billtransaction before entering new data
                        $sql = "DELETE FROM billtransaction WHERE ";
                        $sql .= "FromTime IS NOT NULL AND BillNo IS NULL AND ";
                        $sql .= "StaffID = '" . $_GET['StaffID'] . "' AND ";
                        $sql .= "TransactionDate = '" . $date_text. "'";
                        sql_execute($sql);

                        if ($slot) {
                                // sort $slot by 1st client index , then time slot
                                usort ($slot, "cmp_client_time");

                                // group data in $slot into array $bill which is same structure as table billtransaction
                                $i = 1;
                                foreach ($slot as $transaction) {
                                        $client_index = $transaction['client'];
                                        $from_time = get_time_from_time_slot($transaction['time']);
                                        $to_time = get_time_from_time_slot($transaction['time'] + 1);

                                        if (! $bill) {
                                                // it is the 1st transaction, create array $bill
                                                $bill[$i] = array('CompanyID' => $CompanyID[$client_index],
                                                                        'JobID' => $JobID[$client_index],
                                                                        'ClientID' => $ClientID[$client_index],
                                                                        'ChargeID' => $staff_grade,
                                                                        'StaffID' => $_GET['StaffID'],
                                                                        'ChargeRate' => $ChargeRate[$client_index],
                                                                        'TaxRate' => $TaxRate[$client_index],
                                                                        'TransactionDate' => $date_text,
                                                                        'FromTime' => $from_time,
                                                                        'ToTime' => $to_time,
                                                                        'Remark' => $_SESSION['remark'][$client_index]);
                                        }
                                        else {
                                                if ($transaction['client'] == $last_client_index &&
                                                        $transaction['time'] == $next_time_slot) {
                                                        // time slot is consecutive to last time slot, so just update 'ToTime'
                                                        $bill[$i]['ToTime'] = $to_time;
                                                }
                                                else {
                                                        // difference client or non-consecutive time slot, create a new record
                                                        $i += 1;
                                                        $bill[$i] = array('CompanyID' => $CompanyID[$client_index],
                                                                                'JobID' => $JobID[$client_index],
                                                                                'ClientID' => $ClientID[$client_index],
                                                                                'ChargeID' => $staff_grade,
                                                                                'StaffID' => $_GET['StaffID'],
                                                                                'ChargeRate' => $ChargeRate[$client_index],
                                                                                'TaxRate' => $TaxRate[$client_index],
                                                                                'TransactionDate' => $date_text,
                                                                                'FromTime' => $from_time,
                                                                                'ToTime' => $to_time,
                                                                                'Remark' => $_SESSION['remark'][$client_index]);
                                                }
                                        }
                                        $last_company_index = $transaction['company'];
                                        $last_client_index = $transaction['client'];
                                        $last_job_index = $transaction['job'];
                                        $next_time_slot = $transaction['time'] + 1;
                                }

                                // calculate number of hours and charge rate for each record
                                for ($i = 1; $i <= count($bill); $i++) {
                                        // calculate hours
                                        $begin_slot = get_time_slot_from_time($bill[$i]['FromTime']);
                                        $end_slot = get_time_slot_from_time($bill[$i]['ToTime']);
                                        $bill[$i]['Quantity'] = ($end_slot - $begin_slot) * $_SESSION['TimeSlice'] / 60 ;
                                }

                                //die(var_dump($bill));

                                // save client / time into database
                                foreach ($bill as $bill_transaction) {
                                        $sql = "INSERT INTO billtransaction (CompanyID, JobID, ClientID, ChargeID, ChargeRate, TaxRate,
                                                        StaffID, TransactionDate, FromTime, ToTime, Quantity, Remark, UpdateUser,
                                                        UpdateProgram) VALUES (";
                                        $sql .= "'" . $bill_transaction['CompanyID'] . "', ";
                                        $sql .= "'" . $bill_transaction['JobID'] . "', ";
                                        $sql .= "'" . $bill_transaction['ClientID'] . "', ";
                                        $sql .= "'" . $bill_transaction['ChargeID'] . "', ";
                                        $sql .= $bill_transaction['ChargeRate'] . ", ";
                                        $sql .= $bill_transaction['TaxRate'] . ", ";
                                        $sql .= "'" . $bill_transaction['StaffID'] . "', ";
                                        $sql .= "'" . $bill_transaction['TransactionDate'] . "', ";
                                        $sql .= "'" . $bill_transaction['FromTime'] . "', ";
                                        $sql .= "'" . $bill_transaction['ToTime'] . "', ";
                                        $sql .= $bill_transaction['Quantity'] . ", ";
                                        $sql .= "'" . $bill_transaction['Remark'] . "', ";
                                        $sql .= "'" . $_SESSION['UserID'] . "', ";
                                        $sql .= "'" . $_SERVER['PHP_SELF'] . "')";
                                        sql_execute($sql);
                                }
                        }
                }
                session_unregister('input_client');
                session_unregister('input_time');
                session_unregister('remark');
                echo "<br><br><h1>OK</h1><b>$langtimesheetsaved</b><br><br><a href = 'calendar.php'>$langnewtimesheet</a>";
                ?>
                <!-- AG: redirect to calendar -->
                <script>setTimeout('location.href="calendar.php"',1000);</script>
                <?
                break;

        default :
                // show timesheet for user input

                // load timesheet data if any
                $transaction_date = convert_unix_to_mysql_date($_GET['inputdate']);

                if ($_GET['new']) {
                        unset ($_SESSION['remark']);
                        unset ($_SESSION['grid']);

                        if (! open_period_check($transaction_date)) {
                                message_box("<br>" . $langoutofopenperiod);
                                ?>
                                <script>history.go(-1)</script>
                                <?
                                exit;
                        }
                }

                if (! $_SESSION['input_company'] && ! $_SESSION['input_job'] &&
                        ! $_SESSION['input_client'] && ! $_SESSION['input_time']) {

                        // if the above session variables not found, this program is called from calendar.php
                        // so search from billtransaction to see if any data already saved into database
                        $sql = "SELECT * FROM billtransaction WHERE FromTime is not null AND ";
                        $sql .= "StaffID = '" . $_GET['StaffID'] . "' AND ";
                        $sql .= "TransactionDate = '$transaction_date' ";
                        $sql .= "GROUP BY CompanyID, JobID, ClientID, FromTime ";
                        $sql .= "ORDER BY CompanyID, JobID, ClientID, FromTime";
                        $sql_result = sql_execute($sql);

                        $x = 0;
                        $last_timesheet_column = "";

                        // AG: remove saved data from session if we are modifying existing data
                        $flag_changing = (mysql_affected_rows()>0);
                        if ($flag_changing) {
                                unset($_SESSION["TSsaved"]);
                        }

                        // group billtransaction data into grid format
                        while($sql_data = mysql_fetch_array($sql_result)) {
                                $from_slot = get_time_slot_from_time($sql_data['FromTime']);
                                $to_slot = get_time_slot_from_time($sql_data['ToTime']);

                                if ($last_timesheet_column != $sql_data['CompanyID'] . $sql_data['JobID'] . $sql_data['ClientID']) {
                                        if ($last_timesheet_column != "") $x += 1;
                                        $company[$x] = $sql_data['CompanyID'];
                                        $job[$x] = $sql_data['JobID'];
                                        $client[$x] = $sql_data['ClientID'];
                                        $_SESSION['remark'][$x] = $sql_data['Remark'];
                                        $last_timesheet_column = $sql_data['CompanyID'] . $sql_data['JobID'] . $sql_data['ClientID'];
                                }

                                for ($y = $from_slot ; $y < $to_slot ; $y++) {
                                        if ($sql_data['BillNo']) {
                                                $_SESSION['grid'][$x][$y] = 'BILLED';
                                                $_SESSION['grid'][$x]['billed'] = 1;
                                        }
                                        else $_SESSION['grid'][$x][$y] = 'ON';
                                }

                                if (empty($_SESSION['remark'][$x])) $_SESSION['remark'][$x] = $sql_data['Remark'];
                        }
                }

                // display timesheet
                $target_day = getdate($_GET['inputdate']);
                echo "<br>" . $target_day['mday'] . " " . $target_day['month'] . " " . $target_day['year']
                ?>
                <br><br>
                <form method='GET' name = 'timesheet' action='timesheet.php'>
                <table>
                        <tr>
                                <td><? echo $langstaffid ?> :
                                <td><input type = 'text' name = 'StaffID' value = '<? echo $_GET['StaffID'] ?>' readonly>
                                <td>&nbsp
                                <td><input type = 'submit' value = '<? if ($flag_changing) echo $langmodify; else echo $langsave; ?>'>
                <? // AG: the cancel button is there only on new insert (to prevent session data messin' up)
                if (! $flag_changing) { ?>
                                <td>&nbsp
                                <td><input type = 'button' value = '<? echo $langcancel ?>' onclick='history.go(-1);'>
                <? } ?>
                </table>
                <br>
                <table>
                        <?
                        // display company id row
                        echo "\n<tr bgcolor='$color3'><td width='10%'>$langcompanyid";
                        for ($i = 0; $i < 10; $i++) {
                                echo "\n<td><input type = 'text' size = '8' name = 'Company$i'";

                                // $input_company contains values which are invalid in last form submit
                                if (! empty($_SESSION['input_company'])) {
                                        echo "value = '" . $_SESSION['input_company'][$i] . "'";
                                }
                                // AG: try to restore values from saved $_GET array
                                else if (! empty($_SESSION["TSsaved"]["Company".$i])) {
                                        echo "value = '" . $_SESSION["TSsaved"]["Company".$i] . "'";
                                }
                                else {
                                        // $company contains values entered in last saved timesheet entry
                                        if (! empty($company[$i])) echo "value = '" . $company[$i] . "'";

                                        // if this column contains billed items, cannot change company
                                        if ($_SESSION['grid'][$i]) {
                                                foreach ($_SESSION['grid'][$i] as $y) {
                                                        if ($y == "BILLED") {
                                                                echo " READONLY";
                                                                break;
                                                        }
                                                }
                                        }
                                }
                                echo " >";
                                if ($_SESSION['grid'][$i]['billed'] != 1)
                                        echo "<input type = 'button' value = 'S' onclick=opensearch('company','timesheet.Company$i')>";
                        }

                        // display job id row
                        echo "\n<tr bgcolor='$color3'><td width='10%'>$langjobid";
                        for ($i = 0; $i < 10; $i++) {
                                echo "\n<td><input type = 'text' size = '8' name = 'Job$i'";

                                // $input_job contains values which are invalid in last form sub     it
                                if (! empty($_SESSION['input_job'])) {
                                        echo "value = '" . $_SESSION['input_job'][$i] . "'";
                                }
                                // AG: try to restore values from saved $_GET array
                                else if (! empty($_SESSION["TSsaved"]["Job".$i])) {
                                        echo "value = '" . $_SESSION["TSsaved"]["Job".$i] . "'";
                                }
                                else {
                                        // $job contains values entered in last saved timesheet entry
                                        if (! empty($job[$i])) echo "value = '" . $job[$i] . "'";

                                        // if this column contains billed items, cannot change Job ID
                                        if ($_SESSION['grid'][$i]) {
                                                foreach ($_SESSION['grid'][$i] as $y) {
                                                        if ($y == "BILLED") {
                                                                echo " READONLY";
                                                                break;
                                                        }
                                                }
                                        }
                                }
                                echo " >";
                                if ($_SESSION['grid'][$i]['billed'] != 1)
                                        echo "<input type = 'button' value = 'S' onclick=opensearch('job','timesheet.Job$i')>";
                        }

                        // display client id row
                        echo "\n<tr bgcolor='$color3'><td width='10%'>$langclientid";
                        for ($i = 0; $i < 10; $i++) {
                                echo "\n<td><input type = 'text' size='8' name = 'Client$i'";

                                // $input_client contains values which are invalid in last form submit
                                if (! empty($_SESSION['input_client'])) {
                                        echo "value = '" . $_SESSION['input_client'][$i] . "'";
                                }
                                // AG: try to restore values from saved $_GET array
                                else if (! empty($_SESSION["TSsaved"]["Client".$i])) {
                                        echo "value = '" . $_SESSION["TSsaved"]["Client".$i] . "'";
                                }
                                else {
                                        // $client contains values entered in last saved timesheet entry
                                        if (! empty($client[$i])) echo "value = '" . $client[$i] . "'";

                                        // if this column contains billed items, cannot change Client ID
                                        if ($_SESSION['grid'][$i]) {
                                                foreach ($_SESSION['grid'][$i] as $y) {
                                                        if ($y == "BILLED") {
                                                                echo " READONLY";
                                                                break;
                                                        }
                                                }
                                        }
                                }
                                echo " >";
                                if ($_SESSION['grid'][$i]['billed'] != 1)
                                        echo "<input type = 'button' value = 'S' onclick=opensearch('client','timesheet.Client$i')>";
                        }

                        // display remark row
                        echo "\n<tr bgcolor='$color3'><td>$langremark";
                        for ($i = 0; $i < 10; $i++) {
                                echo "<td><input type = 'button' name = 'remark$i' onclick='remarkchange($i)' ";
                                if (empty($_SESSION['remark'][$i])) echo "value = '$langadd'>\n";
                                else echo "value = '$langmodify'>\n";
                        }
                        echo "\n";

                        // Display time per time slot
                        $total_minutes = ($_SESSION['ToHour'] * 60 + $_SESSION['ToMinute']) -
                                                        ($_SESSION['FromHour'] * 60 + $_SESSION['ToMinute']);
                        $total_time_slot = $total_minutes / $_SESSION['TimeSlice'];

                        // loop to display number of rows
                        for ($y = 0; $y < $total_time_slot ; $y++) {
                                $rowcolor = row_color_change();
                                echo "\n<tr bgcolor='$rowcolor'><td>";
                                $time = get_time_from_time_slot($y);
                                echo $time;

                                // Display check box
                                for ($x = 0; $x < 10 ; $x++) {
                                        echo "<td><input type = 'checkbox'  name = '";
                                        // name of each check box is X?Y???,
                                        // X : x-axis, client column, Y : y-axis, time slice row
                                        echo "X" . $x ;
                                        echo "Y";
                                        echo printf('%03d', $y) . "'";

                                        // $input_time contains values which are invalid in last form submit
                                        if ($_SESSION['input_time']) {
                                                foreach ($_SESSION['input_time'] as $timesheet) {
                                                        if ($timesheet['client'] == $x && $timesheet['time'] == sprintf('%03d',$y))
                                                                echo " CHECKED";
                                                }
                                        }
                                        else {
                                                // $grid contains values entered in last saved timesheet entry
                                                if ($_GET['new']) {
                                                        if ($_SESSION['grid'][$x][$y] == 'ON') echo " CHECKED";
                                                }
                                        }
                                        // AG: default to full day (8 hours)
                                        if (!$flag_changing && ($x==0) && ($y<8)) echo " CHECKED";

                                        if ($_SESSION['grid'][$x][$y] == 'BILLED') echo " DISABLED";
                                        echo ">";
                                }
                        }
                        ?>
                </table>
                <input type = 'hidden' name = 'input_date' value = '<?
                        $unix_date = mktime(0,0,0,$target_day['mon'],$target_day['mday'],$target_day['year']);
                        echo $unix_date ?>'>
                <input type = 'hidden' name = 'action' value = 'save'>
                </form>

                <script>
                        function remarkchange(id) {
                                window.open('timesheetremark.php?remark_id=' + id,'','width=400,height=200');
                        }

                        function opensearch(search_type, fieldname) {
                                url_text = 'search.php?master=' + search_type + '&inputname=' + fieldname;
                                window.open(url_text ,'','width=700,height=500');
                        }
                </script>
                <?
                break;
}
